package com.xqls.controller;

import com.alibaba.fastjson.JSONObject;
import com.xqls.biz.LoginBiz;
import com.xqls.biz.UserBiz;
import com.xqls.dal.model.Login;
import com.xqls.util.CommonResult;
import com.xqls.util.ContextUtil;
import com.xqls.util.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xqls.util.ContextUtil.getTentNo;

@Controller
public class LoginController {

	@Autowired
	private UserBiz userBiz;

	@Autowired
	private LoginBiz loginBiz;
	@Value("${defaultSchema}")
	private String defaultSchema;
	/**
	 * 根据cookie值，访问不同的页面
	 * @param xqlsUserPath
	 * @return String
	 */
	@RequestMapping("toLogin")
	public String login(@CookieValue(value="xqlsUserPath",required=false) String xqlsUserPath, HttpServletResponse response){

		if(StringUtils.isEmpty(xqlsUserPath)){
            try{
                xqlsUserPath=   ContextUtil.getTentNo();
            }catch (Exception e){
            }
            if(StringUtils.isEmpty(xqlsUserPath)){
				return "redirect:/toLogin/"+defaultSchema+".html";
            }
            CookieUtils.addCookie(response,"xqlsUserPath", xqlsUserPath, null);
		}
		return "redirect:/toLogin/"+xqlsUserPath+".html";
	}

	/**
	 * 账户根据租户编号登录系统
	 * 把租户编号放入cookie中
	 * @param userPath
	 * @param response
	 * @param request
	 * @return ModelAndView
	 */
	@RequestMapping("toLogin/{userPath}")
	public ModelAndView toLogin(@PathVariable String userPath, HttpServletResponse response, HttpServletRequest request){
		Subject subject = SecurityUtils.getSubject();
			if (subject.isAuthenticated()) {
				ModelAndView view=new ModelAndView("redirect:/login");
				return  view;
			}

		if(userPath==null||"".equals(userPath)||"null".equals(userPath)){
			return  new ModelAndView("/error/404");
		}
		
		ModelAndView view=new ModelAndView("/login");
		view.addObject("userList", this.userBiz.getList());
		CookieUtils.addCookie(response,"xqlsUserPath", userPath, null);
		return view;
	}

	/**
	 * 通过账户名称和密码，获取账户信息
	 * @param userName
	 * @param password
	 * @param request
	 * @return JSON
	 */
	@RequestMapping("checkLogin/{userName}/{password}")
	@ResponseBody
	public String checkLogin(@CookieValue(value="xqlsUserPath",required=false) String xqlsUserPath,@PathVariable String userName, @PathVariable String password, HttpServletRequest request) {
		try{
	     getTentNo();
		}catch (Exception e){
		}

		CommonResult commonResult = this.loginBiz.doLogin(userName, password);
		return JSONObject.toJSONString(commonResult);
	}

	/**
	 * 判断账户是否有效
	 * 账户有效，则获取与该账户相关角色和权限信息，并将数据与"访问src/mainwebapp/WEB_INF/views/velocity/templates/index.vm"的请求一起传给服务器
	 * 账户无效，则调用被"toLogin"注解的方法
	 * @return ModelAndView
	 */
	@RequestMapping("/login")
	public ModelAndView login() {
		List<Login> loginList=null;
		ModelAndView view = new ModelAndView();
		Map<String, Object> map = new HashMap<String, Object>();
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			map.put("userName", subject.getPrincipal());
			loginList = loginBiz.getLoginByMap(map);
			view.addObject("loginList", loginList);
			if(loginList!=null&&loginList.size()>0){

				view.addObject("name", loginList.get(0).getUser().getName());
			}
			view.setViewName("/index");
		} else {
			subject.logout();
			view.setViewName("redirect:/toLogin");
		}
		return view;
	}

	/**
	 * 账户注销后，访问src/mainwebapp/WEB_INF/views/velocity/templates/toLogin.vm
	 * @return String
	 */
	@RequestMapping("/loginOut")
	public String loginOut() {
		this.loginBiz.loginOut();
		return "redirect:/toLogin.html";
	}

	/**
	 * 账户没有权限，访问src/mainwebapp/WEB_INF/views/velocity/templates/permNo.vm
	 * @return String
	 */
	@RequestMapping("/permNo")
	public String permNo() {
		return "/permNo";
	}
	
	/**
	 * 访问src/mainwebapp/WEB_INF/views/velocity/templates/error/404.vm
	 * @return String
	 */
	@RequestMapping("/building")
    public String building() {
        return "error/404";
    }

	/**
	 * 访问src/mainwebapp/WEB_INF/views/velocity/templates/error/500.vm
	 * @return String
	 */
    @RequestMapping("/error")
    public String error() {
        return "error/500";
    }
}
